/*
 * @Descripttion: 
 * @version: 
 * @Author: 周志伟
 * @Date: 2021-07-06 11:10:54
 * @LastEditors: 周志伟
 * @LastEditTime: 2021-07-07 15:28:56
 */
const Path = require('path');
const Fs = require('fs');

/** config.json 文件路径 */
const configFilePath = Path.join(__dirname, 'config.json');

/** 默认配置 */
const defaultConfig = {
    prefabUuid: null,
    oldUuid: null,
    newUuid: null,
    record: []
};

/** package.json 文件路径 */
const packageFilePath = Path.join(__dirname, 'package.json');

/** package.json 中的 key */
const itemKey = 'zzw/zzw_uuid_replace';

/** 配置管理器 */
const ConfigManager = {

    /**
     * 读取配置
     */
    read() {
        const config = { ...defaultConfig };
        // 配置
        if (Fs.existsSync(configFilePath)) {
            const configData = JSON.parse(Fs.readFileSync(configFilePath));
            config.prefabUuid = configData.prefabUuid;
            config.oldUuid = configData.oldUuid;
            config.newUuid = configData.newUuid;
            config.record = configData.record;
        }
        // 返回配置
        return config;
    },
    /**
     * 保存配置
     */
    save(config) {
        const { oldUuid, newUuid, prefabUuid, record } = config;
        // 配置
        const configData = Fs.existsSync(configFilePath) ? JSON.parse(Fs.readFileSync(configFilePath)) : {};
        if (configData.newUuid !== newUuid || configData.oldUuid !== oldUuid || configData.prefabUuid !== prefabUuid || configData.oldUuid !== record) {
            configData.newUuid = newUuid;
            configData.oldUuid = oldUuid;
            configData.prefabUuid = prefabUuid;
            let _config = this.read();
            configData.record = this.addRecord(_config.record, record);
            this.writeFile(configData)
        }
    },
    /**
     * 对象写入文件
     * @param {*} configData 
     */
    writeFile(configData) {
        Editor.log(configData);
        Fs.writeFileSync(configFilePath, JSON.stringify(configData, null, 2));
    },
    /**
     * 添加操作记录（可以在此方法下添加配置长度限制）
     * @param {*} recordArr 
     * @param {*} configData 
     */
    addRecord(recordArr, record) {
        recordArr.push(record);
        return recordArr;
    }
}

module.exports = ConfigManager;
